import os
from migration.table_migrator import TableMigrator
from migration.view_migrator import ViewMigrator
from migration.trigger_migrator import TriggerMigrator
from migration.routine_migrator import RoutineMigrator

class MetadataMigrator:
    def __init__(self, mysql_db, kingbase_db, migration_config, logger, task_name):
        self.mysql_db = mysql_db
        self.kingbase_db = kingbase_db
        self.migration_config = migration_config
        self.logger = logger
        self.task_name = task_name
        self.target_schema = migration_config.get('target_schema', '')
        
        # 初始化各个迁移器
        self.table_migrator = TableMigrator(mysql_db, kingbase_db, migration_config, logger, task_name)
        self.view_migrator = ViewMigrator(mysql_db, kingbase_db, migration_config, logger, task_name)
        self.trigger_migrator = TriggerMigrator(mysql_db, kingbase_db, migration_config, logger, task_name)
        self.routine_migrator = RoutineMigrator(mysql_db, kingbase_db, migration_config, logger, task_name)
    
    def migrate_metadata(self, tables=None):
        """
        迁移元数据（表结构、视图、触发器、存储过程和函数）
        """
        self.logger.info(f"开始迁移元数据，目标模式: {self.target_schema}")
        
        # 获取需要迁移的表
        if not tables:
            tables = self.table_migrator.get_tables_to_migrate()
        
        # 获取需要处理的视图
        views = self.view_migrator.get_views_to_process()
        
        # 创建目标模式（如果不存在）
        self.logger.info(f"检查并创建目标模式: {self.target_schema}")
        self.kingbase_db.create_schema(self.target_schema)
        
        # 设置搜索路径，确保后续操作在正确的模式下进行
        self.kingbase_db.execute_update(f"SET search_path TO {self.target_schema}, public;")
        
        # 记录创建表的SQL
        create_table_sqls = []
        
        # 迁移每个表的结构
        for table_name in tables:
            try:
                # 使用表迁移器迁移表结构
                create_table_sql, column_comments = self.table_migrator.migrate_table_structure(table_name)
                if create_table_sql:
                    create_table_sqls.append(create_table_sql)
                
                # 迁移索引
                if self.migration_config.get('migrate_indexes', True):
                    self.logger.info(f"开始迁移表索引: {table_name}")
                    indexes = self.mysql_db.get_table_indexes(table_name)
                    if indexes:
                        self.table_migrator.create_indexes(table_name, indexes)
                
            except Exception as e:
                self.logger.error(f"表结构迁移失败: {table_name}\n{e}")
                raise
        
        # 处理视图
        if self.migration_config.get('export_view_sql', True):
            self.logger.info("开始处理视图")
            try:
                # 导出视图SQL到文件
                self.view_migrator.export_view_sqls(views)
                
                # 在数据库中创建视图
                self.logger.info("开始在数据库中创建视图")
                self.view_migrator.create_views_in_database(views)
            except Exception as e:
                self.logger.error(f"视图处理过程中发生错误: {e}")
                # 继续执行其他步骤，不中断整个迁移过程
        
        # 迁移触发器
        if self.migration_config.get('migrate_triggers', False):
            self.logger.info("开始迁移触发器")
            try:
                self.trigger_migrator.migrate_triggers()
            except Exception as e:
                self.logger.error(f"触发器迁移过程中发生错误: {e}")
                # 继续执行其他步骤，不中断整个迁移过程
        
        # 迁移存储过程和函数
        if self.migration_config.get('migrate_procedures_functions', False):
            self.logger.info("开始迁移存储过程和函数")
            try:
                self.routine_migrator.migrate_procedures_functions()
            except Exception as e:
                self.logger.error(f"存储过程和函数迁移失败\n{e}")

        # 保存创建表的SQL到文件
        try:
            self.table_migrator.save_create_table_sqls(create_table_sqls)
        except Exception as e:
            self.logger.error(f"保存SQL文件过程中发生错误: {e}")
            # 记录错误但不中断整个迁移过程
        
        self.logger.info("元数据迁移完成")
        return tables, views
